package com.bdqn.filter;


import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class AuthorizationFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void destroy() {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
        if(httpRequest.getSession().getAttribute("loginUser")==null){
            httpRequest.setCharacterEncoding("text/html;charset=UTF-8");
            PrintWriter printWriter = httpResponse.getWriter();
            printWriter.print("<script>alert('请先进行登陆，再进行后续操作！(Filter 控" +
                    " 制)');location.href='"+httpRequest.getContextPath()+"/login.jsp';</script>");
        }else{
            filterChain.doFilter(httpRequest,httpResponse);
        }
    }
}


